import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { listModels } from "./api";

export const useChatStore = defineStore('chat', () => {
  const models = ref<any>([])
  const chats = ref<any>([])
  const currentChatId = ref('')

  // 读取本地数据
  if (localStorage.getItem('currentChatId')) {
    currentChatId.value = localStorage.getItem('currentChatId') || ''
  }

  function set_chats(data: any) {
    chats.value = data
  }

  function set_currentChatId(id: string) {
    currentChatId.value = id
    localStorage.setItem('currentChatId', id)
  }
  const currentChat = computed(() => {
    if (currentChatId.value && chats.value.length) {
      for (let i = 0; i < chats.value.length; i++) {
        if (chats.value[i].id === currentChatId.value) {
          return chats.value[i]
        }
      }
    }
    return {}
  })

  // 获取模型列表
  function getModelList() {
    if (!models.value.length) {
      function bytesToGB(bytes: number): string {
        return (bytes / 1e9).toFixed(2) + ' GB';
      }
      listModels().then((res: any) => {
        res.models.forEach((item: any) => {
          item.label = item.name + '（' + bytesToGB(item.size) + '）'
          item.value = item.model
        })
        models.value = res.models
      });
    }
  }

  return {
    models,
    chats,
    currentChatId,
    currentChat,
    getModelList,
    set_currentChatId,
    set_chats,
  }
})
